package com.example.music_project

import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.ServiceConnection
import android.os.Bundle
import android.os.IBinder
import android.util.Log
import android.view.View
import android.widget.Button
import android.widget.SeekBar
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import androidx.core.app.NotificationCompat
import androidx.core.content.ContextCompat
import kotlin.concurrent.thread

class MainActivity : AppCompatActivity(), ServiceConnection {

    private var binder: MusicService.MusicBinder? = null
    private val TAG = "MainActivity"
    private val Channel_ID = "Music_Channel"
    private val Notification_ID = 1

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        val no_button = findViewById<Button>(R.id.no_button)
        no_button.setOnClickListener {
            showNotification()
        }

        if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.POST_NOTIFICATIONS) != android.content.pm.PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, arrayOf(android.Manifest.permission.POST_NOTIFICATIONS), 1)
        } else {
            startMusicService()
        }
        if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.READ_EXTERNAL_STORAGE) != android.content.pm.PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, arrayOf(android.Manifest.permission.READ_EXTERNAL_STORAGE), 1)
        } else {
            startMusicService()
        }

        val seekBar = findViewById<SeekBar>(R.id.seekBar)
        seekBar.setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener {
            override fun onProgressChanged(seekBar: SeekBar?, progress: Int, fromUser: Boolean) {
                if (fromUser) {
                    binder?.currentPosition = progress
                }
            }

            override fun onStartTrackingTouch(seekBar: SeekBar?) {
                // mediaPlayer.pause()
            }

            override fun onStopTrackingTouch(seekBar: SeekBar?) {
                // mediaPlayer.start()
            }
        })
    }

    private fun showNotification() {
        val notificationManager: NotificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
        val builder: NotificationCompat.Builder
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
            val channel = NotificationChannel(Channel_ID, "My Channel", NotificationManager.IMPORTANCE_DEFAULT)
            notificationManager.createNotificationChannel(channel)
            builder = NotificationCompat.Builder(this, Channel_ID)
        } else {
            builder = NotificationCompat.Builder(this)
        }
        val intent = Intent(this, MainActivity::class.java)
        val pendingIntent = PendingIntent.getActivity(
            this,
            1,
            intent,
            PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE
        )
        val notification: Notification = builder.setSmallIcon(R.drawable.ic_notification)
            .setContentTitle("Music Player")
            .setContentText("Music is playing")
            .setContentIntent(pendingIntent)
            .build()
        notificationManager.notify(Notification_ID, notification)
    }

    fun startMusicService() {
        val intent = Intent(this, MusicService::class.java)
        intent.putExtra(MusicService.Commond, 1)
        startService(intent)
        bindService(intent, this, Context.BIND_AUTO_CREATE)
    }

    fun onPlay(view: View) {
        val intent = Intent(this, MusicService::class.java)
        intent.putExtra(MusicService.Commond, 1)
        startService(intent)
        showNotification()
    }

    fun onPause(view: View) {
        val intent = Intent(this, MusicService::class.java)
        intent.putExtra(MusicService.Commond, 2)
        startService(intent)
    }

    fun onStop(view: View) {
        val intent = Intent(this, MusicService::class.java)
        intent.putExtra(MusicService.Commond, 3)
        startService(intent)
    }

    fun onNext(view: View) {
        val intent = Intent(this, MusicService::class.java)
        intent.putExtra(MusicService.Commond, 4)
        startService(intent)
    }

    fun onPrev(view: View) {
        val intent = Intent(this, MusicService::class.java)
        intent.putExtra(MusicService.Commond, 5)
        startService(intent)
    }

    override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        if (requestCode == 1 && grantResults.isNotEmpty() && grantResults[0] == android.content.pm.PackageManager.PERMISSION_GRANTED) {
            startMusicService()
        } else {
            Log.e(TAG, "Permissions not granted")
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        unbindService(this)
    }

    override fun onServiceDisconnected(name: ComponentName?) {
        binder = null
    }

    override fun onServiceConnected(name: ComponentName?, service: IBinder?) {
        binder = service as MusicService.MusicBinder
        thread {
            while (binder != null) {
                runOnUiThread {
                    val seekBar = findViewById<SeekBar>(R.id.seekBar)
                    seekBar.max = binder!!.duration
                    seekBar.progress = binder!!.currentPosition
                    val textViewMu = findViewById<TextView>(R.id.textView_mn)
                    textViewMu.text = binder!!.musicName
                    val textViewCurrent = findViewById<TextView>(R.id.textView_count)
                    textViewCurrent.text = "${binder!!.currentIndex + 1}/${binder!!.size}"
                }
                Thread.sleep(1000)
            }
        }
    }
}